package com.studentmanagement.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.studentmanagement.model.Course;
import com.studentmanagement.service.CourseService;
import com.studentmanagement.util.PageBean;

@WebServlet("/course/*")
public class CourseServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private CourseService courseService = new CourseService();
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        
        if (pathInfo == null || pathInfo.equals("/")) {
            // 列出所有课程
            listCourses(request, response);
        } else if (pathInfo.equals("/add")) {
            // 显示添加课程表单
            request.getRequestDispatcher("/WEB-INF/course/add.jsp").forward(request, response);
        } else if (pathInfo.equals("/edit")) {
            // 显示编辑课程表单
            showEditForm(request, response);
        } else if (pathInfo.equals("/delete")) {
            // 删除课程
            deleteCourse(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        
        if (pathInfo == null || pathInfo.equals("/")) {
            // 处理列表页面的分页请求
            listCourses(request, response);
        } else if (pathInfo.equals("/add")) {
            // 添加课程
            addCourse(request, response);
        } else if (pathInfo.equals("/edit")) {
            // 更新课程
            updateCourse(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    private void listCourses(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取分页参数
        int pageNumber = 1;
        int pageSize = 10;
        String sortField = "course_id";
        String sortOrder = "ASC";
        
        try {
            if (request.getParameter("pageNumber") != null) {
                pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
            }
            
            if (request.getParameter("pageSize") != null) {
                pageSize = Integer.parseInt(request.getParameter("pageSize"));
            }
            
            if (request.getParameter("sortField") != null) {
                sortField = request.getParameter("sortField");
            }
            
            if (request.getParameter("sortOrder") != null) {
                sortOrder = request.getParameter("sortOrder");
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        
        // 获取分页数据
        PageBean<Course> pageBean = courseService.getCoursesByPage(pageNumber, pageSize, sortField, sortOrder);
        
        // 将数据存入请求属性
        request.setAttribute("pageBean", pageBean);
        
        // 转发到课程列表页面
        request.getRequestDispatcher("/WEB-INF/course/list.jsp").forward(request, response);
    }
    
    private void showEditForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取课程ID
        int courseId = Integer.parseInt(request.getParameter("id"));
        
        // 获取课程信息
        Course course = courseService.getCourseById(courseId);
        
        if (course != null) {
            // 将课程信息存入请求属性
            request.setAttribute("course", course);
            
            // 转发到编辑页面
            request.getRequestDispatcher("/WEB-INF/course/edit.jsp").forward(request, response);
        } else {
            // 课程不存在，重定向到列表页面
            response.sendRedirect(request.getContextPath() + "/course");
        }
    }
    
    private void addCourse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单数据
        String courseName = request.getParameter("courseName");
        int creditHours = Integer.parseInt(request.getParameter("creditHours"));
        String description = request.getParameter("description");
        String teacher = request.getParameter("teacher");
        
        // 创建课程对象
        Course course = new Course();
        course.setCourseName(courseName);
        course.setCreditHours(creditHours);
        course.setDescription(description);
        course.setTeacher(teacher);
        
        // 添加课程
        boolean success = courseService.addCourse(course);
        
        if (success) {
            // 添加成功，重定向到列表页面
            response.sendRedirect(request.getContextPath() + "/course");
        } else {
            // 添加失败，设置错误消息
            request.setAttribute("error", "添加课程失败");
            request.getRequestDispatcher("/WEB-INF/course/add.jsp").forward(request, response);
        }
    }
    
    private void updateCourse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单数据
        int courseId = Integer.parseInt(request.getParameter("courseId"));
        String courseName = request.getParameter("courseName");
        int creditHours = Integer.parseInt(request.getParameter("creditHours"));
        String description = request.getParameter("description");
        String teacher = request.getParameter("teacher");
        
        // 创建课程对象
        Course course = new Course();
        course.setCourseId(courseId);
        course.setCourseName(courseName);
        course.setCreditHours(creditHours);
        course.setDescription(description);
        course.setTeacher(teacher);
        
        // 更新课程
        boolean success = courseService.updateCourse(course);
        
        if (success) {
            // 更新成功，重定向到列表页面
            response.sendRedirect(request.getContextPath() + "/course");
        } else {
            // 更新失败，设置错误消息
            request.setAttribute("error", "更新课程失败");
            request.setAttribute("course", course);
            request.getRequestDispatcher("/WEB-INF/course/edit.jsp").forward(request, response);
        }
    }
    
    private void deleteCourse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取课程ID
        int courseId = Integer.parseInt(request.getParameter("id"));
        
        // 删除课程
        boolean success = courseService.deleteCourse(courseId);
        
        // 重定向到列表页面
        response.sendRedirect(request.getContextPath() + "/course");
    }
}

